import { RbacMenuBtnType, RbacMenuType } from '@/data/auth/menu';
import { PageParams } from '@/data/result';
import { CorrelationTypeEnum } from '@/enums/auth';
import { useMenus } from '@/hooks/auth/useMenus';
import AddPermModal from '@/pages/auth/rbacMenu/components/AddPermModal';
import AddButtonModal from '@/pages/auth/rbacMenu/components/button/AddButtonModal';
import UpdateButtonModal from '@/pages/auth/rbacMenu/components/button/UpdateButtonModal';
import { tablePage } from '@/services/data';
import { handleAdd, handleRemove, handleRemoveList, handleUpdate } from '@/services/handle';
import { PlusOutlined } from '@ant-design/icons';
import { ActionType, FooterToolbar, ProColumns, ProTable } from '@ant-design/pro-components';
import { Button, Modal } from 'antd';
import React, { useRef, useState } from 'react';

export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<RbacMenuType> & {
    targetKeys?: React.Key[];
  };

export type UpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  visible: boolean;
  values: Partial<RbacMenuType>;
};

const AddButtonTable: React.FC<UpdateFormProps> = (props) => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<RbacMenuBtnType>();
  const [selectedRowsState, setSelectedRows] = useState<RbacMenuBtnType[]>([]);
  const { allMenuValueEnum } = useMenus();
  const [addPermModalVisible, handleAddPermModalVisible] = useState<boolean>(false);

  const columns: ProColumns<RbacMenuBtnType>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '按钮名称',
      dataIndex: 'name',
    },
    {
      title: '按钮标识',
      dataIndex: 'btnPerm',
    },
    {
      title: '归属菜单',
      dataIndex: 'menuId',
      initialValue: props.values.id,
      valueEnum: allMenuValueEnum,
      hideInSearch: true,
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="update"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          更新
        </a>,
        <a
          key="auth"
          onClick={() => {
            handleAddPermModalVisible(true);
            setCurrentRow(record);
          }}
        >
          授权
        </a>,

        <a
          key="remove"
          onClick={async () => {
            await handleRemove('/system/rbacMenuBtn', record.id);
            if (actionRef.current) {
              await actionRef.current.reload();
            }
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <Modal
      width={1200}
      style={{
        padding: '32px 40px 48px',
      }}
      title="添加按钮"
      open={props.visible}
      onCancel={() => {
        props.onCancel();
      }}
      key={`menu-add-button-${props.values?.id || Math.random()}`}
      footer={null}
    >
      <ProTable<RbacMenuBtnType, PageParams>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params) => {
          return tablePage('/system/rbacMenuBtn', params);
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemoveList('/system/rbacMenu', selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}

      <AddButtonModal
        onSubmit={async (value) => {
          const success = await handleAdd('/system/rbacMenuBtn', value);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              await actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        visible={createModalVisible}
        values={{ menuId: props.values.id, name: props.values.name }}
      />
      <UpdateButtonModal
        onSubmit={async (values: any) => {
          const success = await handleUpdate('/system/rbacMenuBtn', values, currentRow);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              await actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />
      <AddPermModal
        onSubmit={async (value) => {
          const permissionIds = value?.targetKeys;
          const menuOrBtnId = currentRow?.id;
          await handleAdd('/system/rbacPermissionMenuBtn', {
            permissionIds,
            menuOrBtnId,
            correlationType: 2,
          });
        }}
        onCancel={() => {
          handleAddPermModalVisible(false);
        }}
        updateModalVisible={addPermModalVisible}
        values={currentRow || {}}
        correlationType={CorrelationTypeEnum.BUTTON}
      />
    </Modal>
  );
};

export default AddButtonTable;
